<template>
  <div style="width: 100%; height: 100%;padding: 10px;">
    <div style="height: 30px;margin-bottom: 10px;">
      <!-- 返回组件 -->
      <a class="back-link" style="color: #f2f2f2;" @click="$router.back()">← Back</a>
      <!-- <router-link to="/" class="back-link" style="color: #f2f2f2;">← Back to List</router-link> -->
    </div>
    <div class="code-preview">
      <!-- 左侧：组件预览 -->
      <div class="preview">
        <div v-if="component" id="preview-container" ref="preview" v-html="component.template"></div>
        <div v-else class="error">❌ 组件 "{{ componentName }}" 未找到或加载失败</div>
      </div>

      <!-- 右侧：代码展示 -->
      <div class="code-container">
        <div class="code-tabs">
          <button @click="activeTab = 'template'" :class="{ active: activeTab === 'template' }">HTML</button>
          <button @click="activeTab = 'script'" :class="{ active: activeTab === 'script' }">JS</button>
          <button @click="activeTab = 'style'" :class="{ active: activeTab === 'style' }">CSS</button>
        </div>

        <div class="code-editor">
          <!-- 复制按钮 -->
          <div class="copy-bar">
            <button class="copy-btn" @click="copyCode" :disabled="copyStatus === 'copied'">
              {{ copyStatus === 'copied' ? '✅ Copied!' : '📋 Copy' }}
            </button>
          </div>

          <!-- 代码块（含行号） -->
          <pre v-if="component && component[activeTab]" class="code-block">
  <code
    :class="`language-${activeTab == 'template' ? 'html' : activeTab == 'script' ? 'javascript' : 'css'}`"
    class="code-content"
    v-html="highlightedCode"></code>
</pre>


          <div v-else class="empty">No {{ activeTab }} code available</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, watch, onUnmounted, computed } from 'vue';
import { useRoute } from 'vue-router';
import hljs from 'highlight.js';
import 'highlight.js/styles/github-dark.min.css';

const route = useRoute();
const componentName = route.params.name;

const activeTab = ref('template');
const component = ref(null);
const error = ref(null);
const copyStatus = ref('idle');
const styleId = ref(null);

// 获取原始内容
const getContent = (tab) => {
  if (!component.value || !component.value[tab]) return '';
  return component.value[tab].trim();
};

// ✅ 计算属性：返回高亮后的 HTML
const highlightedCode = computed(() => {
  const code = getContent(activeTab.value);
  if (!code) return '';
  // 根据 tab 提供语言提示
  const lang = activeTab.value === 'template' ? 'html'
    : activeTab.value === 'script' ? 'javascript'
      : 'css';
  return hljs.highlight(code, { language: lang }).value;
});

// 注入样式（保持你之前的逻辑）
const injectStyle = (css) => {
  if (styleId.value) {
    const old = document.getElementById(styleId.value);
    if (old) old.remove();
    styleId.value = null;
  }
  if (!css || !css.trim()) return;
  const id = `style-${componentName}`;
  const style = document.createElement('style');
  style.id = id;
  style.textContent = css;
  document.head.appendChild(style);
  styleId.value = id;
};

// 加载组件数据
const loadComponent = async () => {
  try {
    const response = await fetch('/code/sources.json');
    console.log('response', response);
    if (!response.ok) throw new Error(`HTTP ${response.status}`);
    const data = await response.json();
    console.log('data', data,componentName);
    if (data[componentName]) {
      component.value = data[componentName];
      console.log('Loaded component:', component.value);
      injectStyle(component.value.style);
    } else {
      console.warn(`Component "${componentName}" not found in JSON`);
      component.value = null;
    }
  } catch (err) {
    console.error('Error loading component:', err);
    error.value = err.message;
    component.value = null;
  }
};

// 复制功能仍然用原始文本
const copyCode = () => {
  const code = getContent(activeTab.value);
  if (!code) return;
  navigator.clipboard.writeText(code)
    .then(() => {
      copyStatus.value = 'copied';
      setTimeout(() => { copyStatus.value = 'idle'; }, 2000);
    })
    .catch(err => {
      console.error('Copy failed: ', err);
      alert('复制失败，请手动选择复制');
    });
};

onMounted(() => {
  loadComponent();
});

watch(() => route.params.name, () => {
  copyStatus.value = 'idle';
  loadComponent();
});

onUnmounted(() => {
  if (styleId.value) {
    const el = document.getElementById(styleId.value);
    if (el) el.remove();
  }
});

</script>

<style scoped>
.code-preview {
  display: flex;
  height: 80vh;
  border: 1px solid #333;
  border-radius: 8px;
  overflow: hidden;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
  background-color: #1a1a1a;
  color: #eee;
}

/* 左侧预览区 */
.preview {
  width: 50%;
  padding: 20px;
  border-right: 1px solid #333;
  /* background-color: #fff; */
  background-color: #212121;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow-y: auto;
}

.preview .error {
  color: #f44336;
  font-size: 14px;
  text-align: center;
}

/* 右侧代码区 */
.code-container {
  width: 50%;
  display: flex;
  flex-direction: column;
  background-color: #1e1e1e;
}

.code-tabs {
  display: flex;
  background-color: #252525;
  border-bottom: 1px solid #444;
}

.code-tabs button {
  padding: 10px 16px;
  border: none;
  background: none;
  cursor: pointer;
  font-size: 14px;
  color: #aaa;
}

.code-tabs button.active {
  background-color: #1e1e1e;
  border-bottom: 2px solid #007acc;
  font-weight: 600;
  color: #007acc;
}

/* 复制按钮栏 */
.copy-bar {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 8px;
  position: absolute;
  z-index: 1;
  right: 2%;
}

.copy-btn {
  padding: 6px 12px;
  font-size: 12px;
  background: #333;
  color: #ddd;
  border: 1px solid #555;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s ease;
}

.copy-btn:hover:not(:disabled) {
  background: #555;
  color: #fff;
}

.copy-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}

/* 代码块：含行号 */
.code-editor {
  flex: 1;
  padding: 10px;
  overflow-y: auto;
  position: relative;
}

.code-block {
  position: relative;
  display: flex;
  margin: 0;
  padding: 16px;
  background-color: #171717;
  /* border: 1px solid #444;
  border-radius: 6px; */
  /* font-family: 'Fira Code', 'Consolas', monospace; */
  font-family: Menlo, Monaco, Consolas, "Andale Mono", "Ubuntu Mono", monospace;
  font-size: 14px;
  line-height: 1.6;
  color: #dcdcdc;
  overflow-x: auto;
  /* 允许长行滚动（但下面隐藏） */
  scrollbar-width: thin;
}

/* 代码内容 */
.code-content {
  flex: 1;
  white-space: pre;
  word-break: break-word;
  overflow-x: hidden;
  color: #dcdcdc;
}

.empty {
  padding: 16px;
  color: #999;
  font-style: italic;
  text-align: center;
}

.back-link {
  text-decoration: none;
  font-size: 14px;
  color: #f2f2f2;
  font-weight: bold;
  width: 100px;
  height: 30px;
  line-height: 20px;
  display: inline-block;
  text-align: center;
  border-radius: 5px;
  padding: 3px;
}

.back-link:hover {
  background-color: rgba(33, 33, 33, 0.8);
  color: #fff;
}

/* 滚动条样式 */
.code-editor::-webkit-scrollbar {
  width: 10px;
}
/* 滚动条两端的按钮（可选，一般隐藏） */
.code-editor::-webkit-scrollbar-button {
  display: none;
}
/* 滚动条的轨道 */
.code-editor::-webkit-scrollbar-track {
  background: #171717;
  border-radius: 6px;
}
.code-editor::-webkit-scrollbar-thumb {
  background: #4e4e4e;
  /* border-radius: 4px; */
}
.code-editor::-webkit-scrollbar-thumb:hover {
  background: #777;
}
</style>